// pages/order-detail/order-detail.js
const { getOrderDetail } = require("../../api/order");
const { handleGlobalError } = require("../../utils/globalErrorHandler");

Page({
  data: {
    orderId: "",
    orderInfo: null,
    items: [],
    orderAddress: null,
    deliveryInfo: null,
    loading: true,
  },

  onLoad(options) {
    const { orderId } = options;
    if (!orderId) {
      wx.showToast({
        title: "订单ID不能为空",
        icon: "none",
      });
      wx.navigateBack();
      return;
    }

    this.setData({ orderId });
    this.loadOrderDetail();
  },

  // 加载订单详情
  async loadOrderDetail() {
    try {
      this.setData({ loading: true });

      const res = await getOrderDetail(this.data.orderId);

      if (res.code === 0) {
        const { orderInfo, items, orderAddress, deliveryInfoVO } = res.data;

        // 处理商品规格文本和订单类型文本
        const processedItems = items.map((item) => {
          if (item.skuSpecs && !item.specsText) {
            item.specsText = this.parseSpecText(item.skuSpecs);
          }
          return item;
        });

        // 处理订单类型文本
        orderInfo.orderTypeText = this.getOrderTypeText(orderInfo.orderType);

        // 处理支付倒计时
        orderInfo.showCountdown = this.shouldShowCountdown(
          orderInfo.orderStatus,
          orderInfo.payExpireTime
        );
        orderInfo.countdownText = this.getCountdownText(
          orderInfo.payExpireTime
        );

        // 处理订单状态文本
        orderInfo.orderStatusText = this.getOrderStatusText(
          orderInfo.orderStatus
        );

        // 处理物流信息中的deliveryContent
        let processedDeliveryInfo = deliveryInfoVO;
        if (deliveryInfoVO && deliveryInfoVO.deliveryContent) {
          try {
            processedDeliveryInfo = {
              ...deliveryInfoVO,
              deliveryContentParsed: JSON.parse(deliveryInfoVO.deliveryContent),
            };
          } catch (error) {
            processedDeliveryInfo = {
              ...deliveryInfoVO,
              deliveryContentParsed: [],
            };
          }
        }

        this.setData({
          orderInfo,
          items: processedItems,
          orderAddress,
          deliveryInfo: processedDeliveryInfo,
        });

        // 启动倒计时定时器
        this.startCountdownTimer();
      } else {
        wx.showToast({
          title: res.message || "获取订单详情失败",
          icon: "none",
        });
      }
    } catch (error) {
      handleGlobalError(error);
    } finally {
      this.setData({ loading: false });
    }
  },

  // 获取状态样式类
  getStatusClass(status) {
    if ([0, 11, 12].includes(status)) return "pending";
    if ([1, 3].includes(status)) return "shipping";
    if (status === 4) return "delivered";
    if ([6, 7, 8].includes(status)) return "refund";
    if ([9, 10].includes(status)) return "completed";
    if ([2, 5].includes(status)) return "closed";
    return "pending";
  },

  // 获取状态表情符号
  getStatusEmoji(status) {
    const emojiMap = {
      0: "⏰",
      1: "📦",
      2: "⏰",
      3: "📦",
      4: "🚚",
      5: "❌",
      6: "🔄",
      7: "💰",
      8: "💰",
      9: "✅",
      10: "🎉",
      11: "⏰",
      12: "❌",
    };
    return emojiMap[status] || "❓";
  },

  // 获取状态描述
  getStatusDesc(status) {
    const descMap = {
      0: "请尽快完成支付，超时订单将自动取消",
      1: "商家正在准备商品，请耐心等待",
      2: "支付超时，订单已自动取消",
      3: "商品已出库，正在准备发货",
      4: "商品正在配送中，请注意查收",
      5: "订单已取消",
      6: "正在处理售后申请",
      7: "部分退款处理中",
      8: "全部退款处理中",
      9: "请确认收货",
      10: "订单已完成，感谢您的购买",
      11: "支付处理中，请稍候",
      12: "支付失败，请重新支付",
    };
    return descMap[status] || "订单状态异常";
  },

  // 获取进度条宽度
  getProgressWidth(status) {
    const widthMap = {
      0: 25,
      1: 25,
      2: 0,
      3: 50,
      4: 75,
      5: 0,
      6: 0,
      7: 0,
      8: 0,
      9: 90,
      10: 100,
      11: 25,
      12: 0,
    };
    return widthMap[status] || 0;
  },

  // 判断是否应该显示倒计时
  shouldShowCountdown() {
    const { orderInfo } = this.data;
    if (!orderInfo) return false;

    // 订单状态必须是未支付状态
    const unpaidStatuses = [0, 11, 12];
    if (!unpaidStatuses.includes(orderInfo.orderStatus)) return false;

    // 必须有支付截止时间
    if (!orderInfo.payExpireTime) return false;

    // 支付截止时间必须大于当前时间
    const now = new Date().getTime();
    const expireTime = new Date(orderInfo.payExpireTime).getTime();
    return expireTime > now;
  },

  // 获取倒计时
  getCountdown(expireTime) {
    if (!expireTime) return "";

    const now = new Date().getTime();
    const expire = new Date(expireTime).getTime();
    const diff = expire - now;

    if (diff <= 0) return "已超时";

    const hours = Math.floor(diff / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((diff % (1000 * 60)) / 1000);

    return `${hours.toString().padStart(2, "0")}:${minutes
      .toString()
      .padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      0: "待付款",
      1: "已付款",
      2: "支付超时",
      3: "已出库",
      4: "已发货",
      5: "已取消",
      6: "申请售后",
      7: "部分退款",
      8: "全部退款",
      9: "确认收货",
      10: "已完成",
      11: "支付中",
      12: "支付失败",
    };
    return statusMap[status] || "未知状态";
  },

  // 解析商品规格文本 - 使用和商品详情页面相同的逻辑
  parseSpecText(specs) {
    try {
      const specObj = JSON.parse(specs);
      const specArray = [];

      for (const key in specObj) {
        if (Array.isArray(specObj[key])) {
          specArray.push(`${key}: ${specObj[key].join(", ")}`);
        } else {
          specArray.push(`${key}: ${specObj[key]}`);
        }
      }

      return specArray.join(" | ");
    } catch (error) {
      console.error("解析规格失败:", error);
      return specs;
    }
  },

  // 获取数据类型
  getDataType(value) {
    if (value === null) return "null";
    if (value === undefined) return "undefined";
    return typeof value;
  },

  // 格式化时间
  formatTime(timeStr) {
    if (!timeStr) return "";
    return timeStr.replace(" ", " ");
  },

  // 格式化物流内容
  formatDeliveryContent(deliveryContentParsed) {
    if (!deliveryContentParsed || !Array.isArray(deliveryContentParsed))
      return [];
    return deliveryContentParsed.map((item) => ({
      time: item.time,
      msg: item.msg,
    }));
  },

  // 获取收货状态文本
  getReceiveStatusText(status) {
    const statusMap = {
      0: "未收货",
      1: "已收货",
    };
    return statusMap[status] || "未知状态";
  },

  // 获取订单类型文本
  getOrderTypeText(orderType) {
    const typeMap = {
      1: "普通订单",
      2: "满减订单",
      3: "折扣订单",
      4: "特价订单",
    };
    return typeMap[orderType] || "普通订单";
  },

  // 获取订单状态文本
  getOrderStatusText(orderStatus) {
    const statusMap = {
      0: "待支付",
      1: "已支付",
      2: "已发货",
      3: "已收货",
      4: "已完成",
      5: "已取消",
      6: "退款中",
      7: "已退款",
      8: "部分退款",
      9: "已支付",
      10: "已支付",
      11: "待支付",
      12: "待支付",
    };
    return statusMap[orderStatus] || "未知状态";
  },

  // 判断是否显示倒计时
  shouldShowCountdown(orderStatus, payExpireTime) {
    if (!payExpireTime) return false;
    const pendingStatuses = [0, 11, 12]; // 待支付状态
    if (!pendingStatuses.includes(orderStatus)) return false;

    const now = new Date().getTime();
    // 转换日期格式以兼容iOS
    const formattedTime = payExpireTime.replace(/-/g, "/");
    const expireTime = new Date(formattedTime).getTime();
    return expireTime > now;
  },

  // 获取倒计时文本
  getCountdownText(payExpireTime) {
    if (!payExpireTime) return "";

    const now = new Date().getTime();
    // 转换日期格式以兼容iOS
    const formattedTime = payExpireTime.replace(/-/g, "/");
    const expireTime = new Date(formattedTime).getTime();
    const diff = expireTime - now;

    if (diff <= 0) return "已超时";

    const minutes = Math.floor(diff / (1000 * 60));
    const seconds = Math.floor((diff % (1000 * 60)) / 1000);

    return `剩余${minutes}分${seconds}秒`;
  },

  // 启动倒计时定时器
  startCountdownTimer() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }

    this.countdownTimer = setInterval(() => {
      const orderInfo = this.data.orderInfo;
      if (orderInfo && orderInfo.showCountdown) {
        const newCountdownText = this.getCountdownText(orderInfo.payExpireTime);
        if (newCountdownText !== orderInfo.countdownText) {
          this.setData({
            "orderInfo.countdownText": newCountdownText,
          });
        }

        // 检查是否已超时
        if (newCountdownText === "已超时") {
          this.setData({
            "orderInfo.showCountdown": false,
          });
        }
      }
    }, 1000);
  },

  // 获取支付方式文本
  getPaymentTypeText(paymentType) {
    const typeMap = {
      1: "微信支付",
      2: "支付宝",
      3: "银行卡",
    };
    return typeMap[paymentType] || "未知支付方式";
  },

  // 判断是否可以支付
  canPay() {
    const { orderInfo } = this.data;
    if (!orderInfo) return false;
    return [0, 11, 12].includes(orderInfo.orderStatus);
  },

  // 判断是否可以取消
  canCancel() {
    const { orderInfo } = this.data;
    if (!orderInfo) return false;
    return [1, 3].includes(orderInfo.orderStatus);
  },

  // 判断是否可以确认收货
  canConfirmReceive() {
    const { orderInfo } = this.data;
    if (!orderInfo) return false;
    return orderInfo.orderStatus === 4;
  },

  // 支付订单
  onPayOrder() {
    wx.showToast({
      title: "跳转到支付页面",
      icon: "none",
    });
    // TODO: 实现支付逻辑
  },

  // 取消订单
  onCancelOrder() {
    wx.showModal({
      title: "确认取消",
      content: "确定要取消这个订单吗？",
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: "订单已取消",
            icon: "success",
          });
          // TODO: 调用取消订单接口
        }
      },
    });
  },

  // 确认收货
  onConfirmReceive() {
    wx.showModal({
      title: "确认收货",
      content: "确定已收到商品吗？",
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: "确认收货成功",
            icon: "success",
          });
          // TODO: 调用确认收货接口
        }
      },
    });
  },

  // 复制订单号
  onCopyOrderNo() {
    const { orderInfo } = this.data;
    if (orderInfo && orderInfo.orderNo) {
      wx.setClipboardData({
        data: orderInfo.orderNo,
        success: () => {
          wx.showToast({
            title: "订单号已复制",
            icon: "success",
          });
        },
      });
    }
  },

  // 复制物流单号
  onCopyDeliveryNo() {
    const { deliveryInfo } = this.data;
    if (deliveryInfo && deliveryInfo.deliveryNo) {
      wx.setClipboardData({
        data: deliveryInfo.deliveryNo,
        success: () => {
          wx.showToast({
            title: "物流单号已复制",
            icon: "success",
          });
        },
      });
    }
  },

  // 查看物流
  onViewDelivery() {
    const { deliveryInfo } = this.data;
    if (deliveryInfo && deliveryInfo.deliveryNo) {
      wx.showToast({
        title: "跳转到物流查询页面",
        icon: "none",
      });
      // TODO: 实现物流查询逻辑
    }
  },

  // 联系商家
  onContactService() {
    wx.showToast({
      title: "跳转到客服页面",
      icon: "none",
    });
    // TODO: 实现联系商家逻辑
  },

  // 申请退款
  onApplyRefund() {
    wx.showModal({
      title: "申请退款",
      content: "确定要申请退款吗？",
      success: (res) => {
        if (res.confirm) {
          // TODO: 调用申请退款接口
          wx.showToast({
            title: "退款申请已提交",
            icon: "success",
          });
        }
      },
    });
  },

  // 申请售后
  onApplyAfterSale() {
    wx.showModal({
      title: "申请售后",
      content: "确定要申请售后吗？",
      success: (res) => {
        if (res.confirm) {
          // TODO: 调用申请售后接口
          wx.showToast({
            title: "售后申请已提交",
            icon: "success",
          });
        }
      },
    });
  },

  // 取消售后
  onCancelAfterSale() {
    wx.showModal({
      title: "取消售后",
      content: "确定要取消售后吗？",
      success: (res) => {
        if (res.confirm) {
          // TODO: 调用取消售后接口
          wx.showToast({
            title: "售后已取消",
            icon: "success",
          });
        }
      },
    });
  },

  // 再次购买
  onBuyAgain() {
    // TODO: 跳转到商品页面或购物车
    wx.showToast({
      title: "跳转到商品页面",
      icon: "success",
    });
  },

  onShow() {
    // 页面显示时重新启动倒计时定时器
    this.startCountdownTimer();
  },

  onHide() {
    // 清理倒计时定时器
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
      this.countdownTimer = null;
    }
  },

  onUnload() {
    // 页面卸载时清理定时器
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
      this.countdownTimer = null;
    }
  },
});
